{% extends "base.html" %}

{% block title %}待办清单 - 生活助手{% endblock %}

{% block content %}
<div class="page-header">
    <div class="d-flex justify-content-between align-items-center">
        <div>
            <h1><i class="bi bi-check-square"></i> 待办清单</h1>
            <p class="text-muted">管理您的任务和待办事项</p>
        </div>
        <div>
            <button class="btn btn-danger btn-custom me-2" onclick="clearCompletedTodos()">
                <i class="bi bi-trash"></i> 清除已完成
            </button>
            <button class="btn btn-primary btn-custom" data-bs-toggle="modal" data-bs-target="#addTodoModal">
                <i class="bi bi-plus-circle"></i> 添加待办
            </button>
        </div>
    </div>
</div>

<!-- 统计卡片 -->
<div class="row mb-4">
    <div class="col-md-3">
        <div class="card text-center">
            <div class="card-body">
                <h3 class="text-primary" id="stat-pending">0</h3>
                <p class="text-muted mb-0">待完成</p>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card text-center">
            <div class="card-body">
                <h3 class="text-success" id="stat-completed">0</h3>
                <p class="text-muted mb-0">已完成</p>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card text-center">
            <div class="card-body">
                <h3 class="text-warning" id="stat-today">0</h3>
                <p class="text-muted mb-0">今日到期</p>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card text-center">
            <div class="card-body">
                <h3 class="text-danger" id="stat-overdue">0</h3>
                <p class="text-muted mb-0">已逾期</p>
            </div>
        </div>
    </div>
</div>

<!-- 过滤和搜索 -->
<div class="card mb-4">
    <div class="card-body">
        <div class="row">
            <div class="col-md-3">
                <select class="form-select" id="filter-priority">
                    <option value="">所有优先级</option>
                    <option value="high">高</option>
                    <option value="medium">中</option>
                    <option value="low">低</option>
                </select>
            </div>
            <div class="col-md-3">
                <select class="form-select" id="filter-category">
                    <option value="">所有分类</option>
                    <option value="工作">工作</option>
                    <option value="生活">生活</option>
                    <option value="学习">学习</option>
                    <option value="其他">其他</option>
                </select>
            </div>
            <div class="col-md-3">
                <select class="form-select" id="filter-status">
                    <option value="">全部状态</option>
                    <option value="pending">待完成</option>
                    <option value="completed">已完成</option>
                </select>
            </div>
            <div class="col-md-3">
                <input type="text" class="form-control" id="search-todo" placeholder="搜索待办...">
            </div>
        </div>
    </div>
</div>

<!-- 待办列表 -->
<div id="todo-list">
    <p class="text-center text-muted">加载中...</p>
</div>

<!-- 添加待办模态框 -->
<div class="modal fade" id="addTodoModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">添加待办事项</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="add-todo-form">
                    <div class="mb-3">
                        <label class="form-label">标题 *</label>
                        <input type="text" class="form-control" id="todo-title" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">描述</label>
                        <textarea class="form-control" id="todo-description" rows="3"></textarea>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">优先级</label>
                        <select class="form-select" id="todo-priority">
                            <option value="low">低</option>
                            <option value="medium" selected>中</option>
                            <option value="high">高</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">分类</label>
                        <select class="form-select" id="todo-category">
                            <option value="工作">工作</option>
                            <option value="生活">生活</option>
                            <option value="学习">学习</option>
                            <option value="其他" selected>其他</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">截止日期</label>
                        <input type="datetime-local" class="form-control" id="todo-deadline">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="addTodo()">添加</button>
            </div>
        </div>
    </div>
</div>

<!-- 编辑待办模态框 -->
<div class="modal fade" id="editTodoModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">编辑待办事项</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="edit-todo-form">
                    <input type="hidden" id="edit-todo-id">
                    <div class="mb-3">
                        <label class="form-label">标题 *</label>
                        <input type="text" class="form-control" id="edit-todo-title" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">描述</label>
                        <textarea class="form-control" id="edit-todo-description" rows="3"></textarea>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">优先级</label>
                        <select class="form-select" id="edit-todo-priority">
                            <option value="low">低</option>
                            <option value="medium">中</option>
                            <option value="high">高</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">分类</label>
                        <select class="form-select" id="edit-todo-category">
                            <option value="工作">工作</option>
                            <option value="生活">生活</option>
                            <option value="学习">学习</option>
                            <option value="其他">其他</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">截止日期</label>
                        <input type="datetime-local" class="form-control" id="edit-todo-deadline">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="updateTodo()">保存</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
let currentTodos = [];

// 加载统计数据
function loadStats() {
    fetch('/todo/api/stats')
        .then(response => response.json())
        .then(data => {
            document.getElementById('stat-pending').textContent = data.pending_count || 0;
            document.getElementById('stat-completed').textContent = data.completed || 0;
            document.getElementById('stat-today').textContent = data.today_deadline || 0;
            document.getElementById('stat-overdue').textContent = data.overdue || 0;
        });
}

// 加载待办列表
function loadTodos() {
    const priority = document.getElementById('filter-priority').value;
    const category = document.getElementById('filter-category').value;
    const status = document.getElementById('filter-status').value;
    const search = document.getElementById('search-todo').value;
    
    let url = '/todo/api/todos?';
    if (priority) url += `priority=${priority}&`;
    if (category) url += `category=${category}&`;
    if (status) url += `status=${status}&`;
    if (search) url += `search=${search}`;
    
    fetch(url)
        .then(response => response.json())
        .then(data => {
            currentTodos = data.todos;
            renderTodos();
        });
}

// 渲染待办列表
function renderTodos() {
    const container = document.getElementById('todo-list');
    
    if (currentTodos.length === 0) {
        container.innerHTML = '<p class="text-center text-muted">暂无待办事项</p>';
        return;
    }
    
    container.innerHTML = currentTodos.map(todo => {
        const priorityClass = `priority-${todo.priority}`;
        const completedClass = todo.completed ? 'completed' : '';
        const deadlineText = todo.deadline ? new Date(todo.deadline).toLocaleString('zh-CN') : '无截止日期';
        
        return `
            <div class="task-item ${completedClass}">
                <div class="d-flex justify-content-between align-items-start">
                    <div class="flex-grow-1">
                        <div class="form-check d-inline-block">
                            <input class="form-check-input" type="checkbox" ${todo.completed ? 'checked' : ''} 
                                   onchange="toggleTodo(${todo.id})">
                        </div>
                        <strong class="ms-2">${todo.title}</strong>
                        <span class="badge ${priorityClass} ms-2">${todo.priority}</span>
                        <span class="badge bg-secondary ms-1">${todo.category}</span>
                        ${todo.description ? `<p class="text-muted ms-4 mb-1 mt-2">${todo.description}</p>` : ''}
                        <small class="text-muted ms-4 d-block">
                            <i class="bi bi-clock"></i> ${deadlineText}
                        </small>
                    </div>
                    <div>
                        <button class="btn btn-sm btn-outline-primary" onclick="editTodoModal(${todo.id})">
                            <i class="bi bi-pencil"></i>
                        </button>
                        <button class="btn btn-sm btn-outline-danger" onclick="deleteTodo(${todo.id})">
                            <i class="bi bi-trash"></i>
                        </button>
                    </div>
                </div>
            </div>
        `;
    }).join('');
}

// 添加待办
function addTodo() {
    const data = {
        title: document.getElementById('todo-title').value,
        description: document.getElementById('todo-description').value,
        priority: document.getElementById('todo-priority').value,
        category: document.getElementById('todo-category').value,
        deadline: document.getElementById('todo-deadline').value
    };
    
    if (!data.title) {
        showAlert('请输入标题', 'warning');
        return;
    }
    
    fetch('/todo/api/todos', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify(data)
    })
    .then(response => response.json())
    .then(result => {
        if (result.success) {
            showAlert('添加成功', 'success');
            bootstrap.Modal.getInstance(document.getElementById('addTodoModal')).hide();
            document.getElementById('add-todo-form').reset();
            loadTodos();
            loadStats();
        }
    });
}

// 切换完成状态
function toggleTodo(id) {
    fetch(`/todo/api/todos/${id}/toggle`, {
        method: 'POST'
    })
    .then(response => response.json())
    .then(result => {
        if (result.success) {
            loadTodos();
            loadStats();
        }
    });
}

// 编辑待办模态框
function editTodoModal(id) {
    const todo = currentTodos.find(t => t.id === id);
    if (!todo) return;
    
    document.getElementById('edit-todo-id').value = todo.id;
    document.getElementById('edit-todo-title').value = todo.title;
    document.getElementById('edit-todo-description').value = todo.description || '';
    document.getElementById('edit-todo-priority').value = todo.priority;
    document.getElementById('edit-todo-category').value = todo.category;
    
    if (todo.deadline) {
        const deadline = new Date(todo.deadline);
        // 格式化为本地时间（datetime-local格式：YYYY-MM-DDTHH:mm）
        const year = deadline.getFullYear();
        const month = String(deadline.getMonth() + 1).padStart(2, '0');
        const day = String(deadline.getDate()).padStart(2, '0');
        const hours = String(deadline.getHours()).padStart(2, '0');
        const minutes = String(deadline.getMinutes()).padStart(2, '0');
        document.getElementById('edit-todo-deadline').value = `${year}-${month}-${day}T${hours}:${minutes}`;
    }
    
    new bootstrap.Modal(document.getElementById('editTodoModal')).show();
}

// 更新待办
function updateTodo() {
    const id = document.getElementById('edit-todo-id').value;
    const data = {
        title: document.getElementById('edit-todo-title').value,
        description: document.getElementById('edit-todo-description').value,
        priority: document.getElementById('edit-todo-priority').value,
        category: document.getElementById('edit-todo-category').value,
        deadline: document.getElementById('edit-todo-deadline').value
    };
    
    fetch(`/todo/api/todos/${id}`, {
        method: 'PUT',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify(data)
    })
    .then(response => response.json())
    .then(result => {
        if (result.success) {
            showAlert('更新成功', 'success');
            bootstrap.Modal.getInstance(document.getElementById('editTodoModal')).hide();
            loadTodos();
        }
    });
}

// 删除待办
function deleteTodo(id) {
    if (!confirm('确定要删除这个待办事项吗？')) return;
    
    fetch(`/todo/api/todos/${id}`, {
        method: 'DELETE'
    })
    .then(response => response.json())
    .then(result => {
        if (result.success) {
            showAlert('删除成功', 'success');
            loadTodos();
            loadStats();
        }
    });
}

// 一键清除已完成的待办
function clearCompletedTodos() {
    if (!confirm('确定要清除所有已完成的待办事项吗？此操作不可恢复。')) return;
    
    fetch('/todo/api/todos/clear-completed', {
        method: 'DELETE'
    })
    .then(response => response.json())
    .then(result => {
        if (result.success) {
            showAlert(`成功清除 ${result.count} 个已完成的待办事项`, 'success');
            loadTodos();
            loadStats();
        }
    });
}

// 页面加载完成
document.addEventListener('DOMContentLoaded', function() {
    loadTodos();
    loadStats();
    
    // 绑定过滤器事件
    document.getElementById('filter-priority').addEventListener('change', loadTodos);
    document.getElementById('filter-category').addEventListener('change', loadTodos);
    document.getElementById('filter-status').addEventListener('change', loadTodos);
    document.getElementById('search-todo').addEventListener('input', loadTodos);
});
</script>
{% endblock %}

